Completed
Push — master ( d83c14...87c801 )
by Jan
16s queued 16s
created

promises.ts ➔ makePromise   A

Complexity

Conditions 2

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 9
dl 0
loc 12
rs 9.95
c 0
b 0
f 0
1
import { WriteTags } from '../types/Tags'
2
import { Options } from '../types/Options'
3
import { create } from "./create"
4
import { read, ReadCallback } from "./read"
5
import { removeTags } from "./remove"
6
import { update } from "./update"
7
import { write, WriteCallback } from "./write"
8
9
type Settle<T> = {
10
    (error: NodeJS.ErrnoException | Error, result: null): void
11
    (error: null, result: T): void
12
}
13
14
function makePromise<T>(callback: (settle: Settle<T>) => void) {
15
    return new Promise<T>((resolve, reject) => {
16
        callback((error, result) => {
17
            if(error) {
18
                reject(error)
19
            } else {
20
                // result can't be null here according the Settle callable
21
                // type but TS can't evaluate it properly here, so use the
22
                // null assertion, and then disable the lint error.
23
                // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
24
                resolve(result!)
25
            }
26
        })
27
    })
28
}
29
30
export const Promises = {
31
    create: (tags: WriteTags) =>
32
        makePromise((settle: Settle<Buffer>) =>
33
            create(tags, result => settle(null, result)),
34
    ),
35
    write: (tags: WriteTags, filebuffer: string | Buffer) =>
36
        makePromise<Buffer>((callback: WriteCallback) =>
37
            write(tags, filebuffer, callback)
38
        ),
39
    update: (tags: WriteTags, filebuffer: string | Buffer, options?: Options) =>
40
        makePromise<Buffer>((callback: WriteCallback) =>
41
            update(tags, filebuffer, options ?? {}, callback)
42
        ),
43
    read: (file: string, options?: Options) =>
44
        makePromise((callback: ReadCallback) =>
45
            read(file, options ?? {}, callback)
46
        ),
47
    removeTags: (filepath: string) =>
48
        makePromise((settle: Settle<void>) =>
49
            removeTags(
50
                filepath,
51
                (error) => error ? settle(error, null) : settle(null)
52
            )
53
        )
54
} as const
55
56
/**
57
 * @deprecated consider using `Promises` instead, `Promise` creates conflict
58
 *             with the Javascript native promise.
59
 */
60
export { Promises as Promise }
61